﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.ServiceLocation;

namespace EF4.Core.IoC
{
   
    public class IoCContainer
    {
        // Fields
        private static volatile IServiceLocator currentContainer;
        private static readonly object currentContainerLock = new object();

        // Methods
        public static IServiceLocator CreateDefaultContainer()
        {
            string assemblyName = ServiceLocatorConfigurationSection.GetInstance().Type.Split(new char[] { ',' })[1];
            string typeName = ServiceLocatorConfigurationSection.GetInstance().Type.Split(new char[] { ',' })[0];
            currentContainer = (IServiceLocator)Activator.CreateInstance(assemblyName, typeName).Unwrap();
            return currentContainer;
        }

        private static void SetCurrentContainerIfNotSet()
        {
            if (currentContainer == null)
            {
                lock (currentContainerLock)
                {
                    if (currentContainer == null)
                    {
                        currentContainer = CreateDefaultContainer();
                    }
                }
            }
        }

        // Properties
        public static IServiceLocator Current
        {
            get
            {
                SetCurrentContainerIfNotSet();
                return currentContainer;
            }
            set
            {
                lock (currentContainerLock)
                {
                    currentContainer = value;
                }
            }
        }
    }



}
